package com.n.passwordbook.Utils;

import com.n.passwordbook.Launcher;
import javafx.scene.image.Image;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Objects;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Helper
{
    private static File jarFile;

    public static String ProjectPath;
    public static String Version;
    public static Image Icon;
    public static FileLock lock;

    public static long StartTimes;

    static
    {
        jarFile = new File(URLDecoder.decode(Helper.class.getProtectionDomain().getCodeSource().getLocation().getPath(), StandardCharsets.UTF_8));
        Icon = new Image(Objects.requireNonNull(Launcher.class.getResourceAsStream("resource/icon.png")));
        ProjectPath = "com/n/passwordbook";
        Version = "1.0.0.0";
    }

    public static String getJARPath()
    {
        return System.getProperty("user.dir");
    }

    public static <T> T getSpecialType(T __Ty, Object o)
    {
        if (__Ty.getClass().getSimpleName().equals(o.getClass().getSimpleName()))
        {
            return (T) o;
        }
        return null;
    }

    public static <T> T getSpecialTypeUnsafe(T __Ty, Object o)
    {
        return (T) o;
    }

    public static File selectPasswordBookFile()
    {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        fileChooser.setTitle("选择一个密码本");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("密码本文件", "*.pb"),
                new FileChooser.ExtensionFilter("所有文件", "*.*")
        );
        return fileChooser.showOpenDialog(new Stage());
    }

    public static File selectPasswordBookFile(String title)
    {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        fileChooser.setTitle(title);
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("密码本文件", "*.pb"),
                new FileChooser.ExtensionFilter("所有文件", "*.*")
        );
        return fileChooser.showOpenDialog(new Stage());
    }

    public static File selectPasswordBookFileAs(String title)
    {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        fileChooser.setTitle(title);
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("密码本文件", "*.pb"),
                new FileChooser.ExtensionFilter("csv(UTF-8编码)文件", "*.csv")
        );
        return fileChooser.showSaveDialog(new Stage());

    }

    public static File selectPasswordBookPath(String title)
    {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle(title);
        directoryChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        return directoryChooser.showDialog(new Stage());
    }

    public static String getFileNameWithoutExtensionName(String fileName)
    {
        int dot = fileName.lastIndexOf('.');
        if ((dot > -1) && (dot < (fileName.length())))
        {
            return fileName.substring(0, dot);
        }
        return fileName;
    }

    public static ArrayList<String> getFileNamesInJarDirectory(String fullPathInJAR)
    {
        var ret = new ArrayList<String>();
        var path = fullPathInJAR + "/";
        if (jarFile.isFile())//打包后运行
        {
            final JarFile jar;
            try
            {
                jar = new JarFile(jarFile);
                final Enumeration<JarEntry> entries = jar.entries();
                while (entries.hasMoreElements())
                {
                    final String name = entries.nextElement().getName();
                    if (name.startsWith(path) && !name.equals(path))
                    {
                        ret.add(getFileNameWithoutExtensionName(StringUtils.substringAfterLast(name, '/')));
                    }
                }
                jar.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        else//调试时运行
        {
            final URL url = Helper.class.getResource("/" + fullPathInJAR);
            assert url != null;
            try
            {
                final var files = new File(url.toURI()).listFiles();
                assert files != null;
                for (var file : files)
                {
                    ret.add(getFileNameWithoutExtensionName(file.getName()));
                }
            }
            catch (URISyntaxException ex)
            {
                ex.printStackTrace();
            }
        }
        return ret;
    }

    public static void checkAppNOTStarted()
    {
        var file = new File("PasswordBook.lock");
        try
        {
            var fos = new FileOutputStream(file);

            lock = fos.getChannel().tryLock();
            if (lock == null)
            {
                System.exit(3);
            }
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
            System.exit(2);
        }
    }
}
